<template>
	<view class="page-b">

		<!-- 搜索框 -->
		<view class="tn-classify__search--wrap">
			<view class="tn-color-gray--dark "
				style="margin: 20rpx 30rpx 0rpx 30rpx;border-radius: 100rpx;padding-left: 6rpx;background-color: rgba(248, 247, 248, 0.9);">
				<view class="tn-padding-xs">
					<tn-input v-model="search.name" placeholder="请搜索" @blur="getGetenterprisePolicy()" />
				</view>

			</view>
		</view>
		<view class="tabs tn-text-center tn-text-md tn-padding-sm tn-flex tn-flex-col-center">
			<view class="tabs-item tn-padding-sm" @click="openPrpup(0)">
				<text>{{search.projectName}}</text>
				<text class="tn-icon-down"></text>
			</view>
			<view class="tabs-item tn-padding-sm" @click="openPrpup(1)">
				<text>{{search.documentCategoryName}}</text>
				<text class="tn-icon-down"></text>
			</view>
			<view class="tabs-item tn-padding-sm" @click="openPrpup(2)">
				<text>{{searchRegion}}</text>
				<text class="tn-icon-down"></text>
			</view>
		</view>
		<!-- 分类列表和内容 -->
		<view class="tn-classify__container">
			<view class="tn-classify__container__wrap tn-flex tn-flex-nowrap tn-flex-row-around tn-bg-white">
				<!-- 左边容器 -->
				<scroll-view class="tn-classify__left-box left-width tn-bg-gray--light" :scroll-top="leftScrollViewTop"
					scroll-y scroll-with-animation :style="{height: scrollViewHeight + 'px'}">
					<view v-for="(item, index) in tabbar" :key="index" :id="`tabbar_item_${index}`"
						class="tn-classify__tabbar__item tn-flex tn-flex-col-center tn-flex-row-center"
						:class="[tabbarItemClass(index)]" @tap.stop="clickClassifyNav(index)">
						<view class="tn-classify__tabbar__item__title">{{ item.name }}</view>
					</view>
				</scroll-view>

				<!-- 右边容器 -->
				<scroll-view class="" scroll-y :scroll-top="rightScrollViewTop"
					:style="{height: scrollViewHeight + 'px'}">
					<block>
						<view class="tn-classify__content" @click="tn('/preferredPages/product')">
							<view
								class="tn-classify__content__sub-classify__content   tn-flex tn-flex-wrap tn-flex-col-center tn-flex-row-left">

								<view v-for="(sub_item,sub_index) in subClassify" :key="sub_index"
									class="box tn-text-md tn-flex tn-flex-col-center tn-padding-left-xs tn-padding-right-xs">
									<view class="left">
										<image style="width: 80rpx;height: 80rpx;" src="/static/images/pdf.png"></image>
									</view>
									<view class="right tn-padding-sm">
										<view class="title tn-text-md" style="line-height: 50rpx;">
											{{ sub_item.name }}
										</view>
										<view class="tn-flex tn-flex-row-between tn-margin-top-sm">
											<view class="label .tn-text-sm">{{sub_item.label}}</view>
											<view class="btnright">
												<tn-button borderBold backgroundColor="#63a7ff" fontColor="#fff"
													@click="open(sub_item)">查看</tn-button>
												<tn-button class="tn-margin-left-sm" borderBold backgroundColor="#ff3b21" fontColor="#fff"
													@click="Download(sub_item)">下载</tn-button>
											</view>
										</view>
									</view>
								</view>
							</view>
						</view>
					</block>
				</scroll-view>
			</view>
		</view>
		<catePrpup ref="catePrpup" @emitLabel="emitLabel"></catePrpup>
		<addressPrpup ref="addressPrpup" @updataAddress="updataAddress"></addressPrpup>
	</view>

	</view>
</template>

<script>
	import {
		GetenterprisePolicyCategory,
		GetenterprisePolicy,
		GetdocumentCategory
	} from '@/api/Property/index.js'
	import catePrpup from './components/catePrpup.vue'
	import addressPrpup from './components/addressPrpup.vue'
	export default {
		name: 'templateShopClassify',
		components: {
			catePrpup,
			addressPrpup
		},
		data() {
			return {
				searlist: [
					'搜索',
				],
				search: {
					name: '',
					documentCategoryId: '',
					documentCategoryName: '',
					projectName: '',
					projectId: '',

				},
				// 侧边栏分类数据
				tabbar: [],
				// 分类里面的内容信息
				// 每个子栏目下的内容
				subClassify: [],
				// 分类菜单item的信息
				tabbarItemInfo: [],
				// scrollView的top值
				scrollViewBasicTop: 0,
				// scrollView的高度
				scrollViewHeight: 0,
				// 左边scrollView的滚动高度
				leftScrollViewTop: 0,
				// 右边scrollView的滚动高度
				rightScrollViewTop: 0,
				// 当前选中的tabbar序号
				currentTabbarIndex: 0,
				//id
				categoryId: '',
				//搜索map
				searchMap: {
					0: '项目适配',
					1: '发文类别',
					2: '国家级'
				},
				//发文
				documentList: [],
				//项目范围
				projceList: [{
					name: '全部范围',
					id: 1
				}, {
					name: '项目区分',
					id: 2
				}],
				defaultName: {
					cname: '区域'
				},
				//省
				provinceId: {},
				//市
				cityId: {},
				//区
				districtId: {},
				//区域搜索类型
				typeToPropertiesMap: [
					['defaultName'],
					['provinceId'],
					['provinceId', 'cityId'],
					['provinceId', 'cityId', 'districtId']
				],
				//区域搜索下标
				typeToPropertiesIndex: 0
			}
		},
		computed: {
			searchRegion() {
				const properties = this.typeToPropertiesMap[this.typeToPropertiesIndex];
				let regionName = '';

				properties.forEach(property => {
					if (this[property] && this[property].cname) {
						if (regionName) {
							regionName += '/';
						}
						regionName += this[property].cname;
					}
				});

				return regionName.trim();
			},
			tabbarItemClass() {
				return index => {
					if (index === this.currentTabbarIndex) {
						return 'tn-classify__tabbar__item--active tn-bg-white'
					} else {
						let clazz = 'tn-bg-gray--light'
						if (this.currentTabbarIndex > 0 && index === this.currentTabbarIndex - 1) {
							clazz += ' tn-classify__tabbar__item--active--prev'
						}
						if (this.currentTabbarIndex < this.tabbar.length && index === this.currentTabbarIndex + 1) {
							clazz += ' tn-classify__tabbar__item--active--next'
						}
						return clazz
					}
				}
			}
		},
		mounted() {
			this.$nextTick(() => {
				this.getScrollViewInfo()
				this.getTabbarItemRect()
			})
		},
		onShow() {
			this.getCateGory()
			this.getdocumentCategory()
			this.search.projectName = '全部范围'
			this.search.documentCategoryName = '发文列表'
		},
		methods: {
			getCateGory() {
				let param = {
					pageable: 0
				}
				GetenterprisePolicyCategory(param).then((res) => {
					this.tabbar = res.data
					this.categoryId = res.data[this.currentTabbarIndex].id
					this.getGetenterprisePolicy()
				})
			},
			getGetenterprisePolicy() {
				let param = {
					categoryId: this.categoryId,
					documentCategoryId: this.search.documentCategoryId,
					pageable: 0,
					provinceId: this.provinceId.id || "",
					cityId: this.cityId.id || "",
					districtId: this.districtId.id || "",
					level: this.typeToPropertiesIndex,
					name: this.search.name
				}
				GetenterprisePolicy(param).then((res) => {
					this.subClassify = res.data
				})
			},
			getdocumentCategory() {
				GetdocumentCategory().then((res) => {
					let list = [{
						name: '全部类别',
						id: ''
					}]
					this.documentList = list.concat(res.data)
				})
			},
			//区域搜索
			updataAddress(data, type) {
				const properties = ['defaultName', 'provinceId', 'cityId', 'districtId'];
				// 初始化所有属性为默认值（空字符串）
				properties.forEach(prop => {
					this[prop] = {};
				});
				//0 国家 1省 2市 3区
				let Arrlist = []
				this.typeToPropertiesIndex = type
				Arrlist = this.typeToPropertiesMap[type] || [];
				data.forEach((value, index) => {
					if (index < Arrlist.length) {
						this[Arrlist[index]] = value;
					}
				});
				this.getGetenterprisePolicy()
			},
			emitLabel(type, item) {
				switch (type) {
					case 1:
						this.search.documentCategoryName = item.name
						this.search.documentCategoryId = item.id
						break;
					case 0:
						this.search.projectName = item.name
						this.search.projectId = item.id
						break;
				}
				this.getGetenterprisePolicy()
			},
			openPrpup(type) {
				let title = this.searchMap[type]
				let index;
				switch (type) {
					case 1:
						index = this.documentList.findIndex((i) => i.id == this.search.documentCategoryId)
						this.$refs['catePrpup'].openPrpup(title, this.documentList, index, type);
						break;
					case 0:
						index = this.projceList.findIndex((i) => i.id == this.search.projectId)
						this.$refs['catePrpup'].openPrpup(title, this.projceList, index, type);
						break;
					case 2:
						const properties = [this.address, this.city, this.state, this.zip];
						this.$refs['addressPrpup'].openPrpup(properties);
						break;
				}
			},
			Download(item) {
				uni.downloadFile({
					url: item.fileUrl,
					success: function(res) {
						var filePath = res.tempFilePath;
						uni.openDocument({
							filePath: filePath,
							showMenu: true,
							success: function(res) {
								console.log('下载文档成功');
							}
						});
					}
				});
			},
			open(item) {
				uni.navigateTo({
					url: `/pages/policy/details?id=${item.id}`
				});

			},
			// 跳转
			tn(e) {
				uni.navigateTo({
					url: e,
				});
			},

			// 获取scrollView的高度信息
			getScrollViewInfo() {
				// 获取搜索栏的bottom信息，然后用整个屏幕的可用高度减去bottom的值即可获取scrollView的高度(防止双重滚动)
				this._tGetRect('.tn-classify__search--wrap').then((rect) => {
					// 如果获取失败重新获取
					if (!rect) {
						setTimeout(() => {
							this.getScrollViewInfo()
						}, 10)
						return
					}
					// 获取当前屏幕的可用高度
					const systemInfo = uni.getSystemInfoSync()
					this.scrollViewBasicTop = systemInfo.statusBarHeight + rect.bottom + uni.upx2px(10)
					this.scrollViewHeight = systemInfo.safeArea.height + systemInfo.statusBarHeight - rect.bottom -
						uni.upx2px(10) - 49
				})
			},
			// 获取分类菜单每个item的信息
			getTabbarItemRect() {
				let view = uni.createSelectorQuery().in(this)
				for (let i = 0; i < this.tabbar.length; i++) {
					view.select('#tabbar_item_' + i).boundingClientRect()
				}
				view.exec(res => {
					if (!res.length) {
						setTimeout(() => {
							this.getTabbarItemRect()
						}, 10)
						return
					}

					// 将每个分类item的相关信息
					res.map((item) => {
						this.tabbarItemInfo.push({
							top: item.top,
							height: item.height
						})
					})
				})
			},
			// 点击了分类导航
			clickClassifyNav(index) {
				if (this.currentTabbarIndex === index) {
					return
				}
				this.currentTabbarIndex = index

				this.handleLeftScrollView(index)
				this.switchClassifyContent()
			},
			// 点击分类后，处理scrollView滚动到居中位置
			handleLeftScrollView(index) {
				const tabbarItemTop = this.tabbarItemInfo[index].top - this.scrollViewBasicTop
				if (tabbarItemTop > this.scrollViewHeight / 2) {
					this.leftScrollViewTop = tabbarItemTop - (this.scrollViewHeight / 2) + this.tabbarItemInfo[index]
						.height
				} else {
					this.leftScrollViewTop = 0
				}
			},
			// 切换对应分类的数据
			switchClassifyContent() {
				this.rightScrollViewTop = 1
				this.$nextTick(() => {
					this.rightScrollViewTop = 0
				})
				this.categoryId = this.tabbar[this.currentTabbarIndex].id
				this.getGetenterprisePolicy()
			}
		}
	}
</script>

<style lang="scss" scoped>
	.box {
		min-height: 200rpx;
		width: 100%;
		margin: 10rpx;
		border-bottom: 2rpx solid #c7c7c7;

		.left {}

		.right {
			height: 100%;
			width: 100%;

			.label {
				color: red;
			}
		}
	}

	.tabs {
		.tabs-item {
			width: 33.3%;
		}

	}

	.page-b {
		max-height: 100vh;
	}

	.left-width {
		flex-basis: 28%;
	}

	/* 自定义导航栏内容 end */
	.tn-classify {

		/* 搜索栏 start */
		&__search {
			&--wrap {}

			&__box {
				flex: 1;
				text-align: center;
				padding: 20rpx 30rpx;
				margin: 0 30rpx;
				border-radius: 60rpx;
				font-size: 30rpx;
			}

			&__icon {
				padding-right: 10rpx;
			}

			&__text {
				padding-right: 10rpx;
			}
		}

		&__container {}

		&__left-box {}

		&__right-box {
			background-color: #FFFFFF;
		}

		/* 分类列表和内容 end */

		/* 侧边导航 start */
		&__tabbar {
			&__item {
				height: 110rpx;

				&:first-child {
					border-top-right-radius: 0rpx;
				}

				&:last-child {
					border-bottom-right-radius: 0rpx;
				}

				&--active {
					background-color: #FFFFFF;
					position: relative;
					// font-weight: bold;
					color: #3668FC;

					&::before {
						content: '';
						position: absolute;
						width: 12rpx;
						height: 40rpx;
						top: 50%;
						left: 0;
						background-color: #3668FC;
						border-radius: 12rpx;
						transform: translateY(-50%) translateX(-50%);
					}

					&--prev {
						border-bottom-right-radius: 26rpx;
					}

					&--next {
						border-top-right-radius: 26rpx;
					}
				}
			}
		}

		/* 侧边导航 end */

		/* 分类内容 start */
		&__content {
			margin: 18rpx;

			/* 推荐商品 start */
			&__recomm {
				margin-bottom: 40rpx;

				&__swiper {}
			}

			/* 推荐商品 end */

			/* 子栏目 start */
			&__sub-classify {
				margin-bottom: 20rpx;
				padding-bottom: 40rpx;

				&--title {
					font-weight: bold;
					margin-bottom: 18rpx;

				}

				&__content {

					&__item {
						width: 50%;
					}

					&__image {
						background-color: rgba(188, 188, 188, 0.1);
						border-radius: 10rpx;
						margin: 10rpx 10rpx 0 10rpx;
						margin-left: 0;
						width: 100%;
						height: 340rpx;
						overflow: hidden;
						border: 1rpx solid rgba(0, 0, 0, 0.02);

						image {
							width: 100%;
							height: 340rpx;
						}
					}

					&__title {
						margin-right: 10rpx;
					}
				}
			}

			/* 子栏目 end */
		}

		/* 分类内容 end */
	}
</style>